/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.controller

import org.ibiblio.terasaur.bt.Torrent
import org.ibiblio.terasaur.item.Item
import org.grails.plugins.lookups.Lookup
import org.springframework.security.access.AccessDeniedException
import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils

class ApiMixin {
    public Map itemToMap(Item item, boolean canEdit) {
        if (!item) {
            return [:]
        }
        def username = ''
        if (item.owner) {
            username = item.owner.username
        }
        Map result = [
            id: item.id,
            type: [id: item.type, name: Lookup.valueForCode('item.type', item.type)],
            title: item.title,
            description: item.description,
            language: item.language,
            license: [id: item.license, name: Lookup.valueForCode('item.license', item.license)],
            published: item.published.toString(),
            owner: username,
            deleted: item.deleted,
            collection: [id: item.collection.id, name: item.collection.name],
            dateCreated: item.dateCreated.toString(),
            lastUpdated: item.lastUpdated.toString(),
            downloads: _getDownloads(item, canEdit)
            ]

        return result
    }

    public List _getDownloads(Item item, boolean canEdit) {
        def downloadsParams = [
            'offset': 0,
            'max': 10,
            'item': item,
            'canEditItem': true
            ]
        List downloadsList = itemService.downloads(downloadsParams)
        List result = []
        downloadsList.each {torrent->
            result << torrentToMap(torrent)
        }
        return result
    }

    public Map torrentToMap(Torrent torrent) {
        Map result = [
            infoHash: torrent.infoHash,
            name: torrent.name,
            size: torrent.size,
            filesize: torrent.filesize,
            published: torrent.published,
            dateCreated: torrent.dateCreated,
            lastUpdated: torrent.lastUpdated
            ]
        return result
    }

    /**
     * Function to execute authentication checks for the json api controllers
     * since the standard Secured decorators produce unwanted redirects.
     */
    public void apiAuthenticationCheck() {
        if (!springSecurityService.currentUser) {
            throw new AccessDeniedException(message(code:'login.required.error.message'))
        }
        if (!SpringSecurityUtils.ifAnyGranted('ROLE_ADMIN, ROLE_CAN_CREATE_ITEM')) {
            throw new AccessDeniedException(message(code:'item.permission.denied.message'))
        }
    }

    public List getItemFieldErrors(Item item) {
        List errors = []
        item.errors.fieldErrors.each {error->
            errors << [field:error.field, value:error.rejectedValue]
        }
        return errors
    }
}

